package com.zyp.weibo_demo1.controller;

import com.zyp.weibo_demo1.mapper.CommentMapper;
import com.zyp.weibo_demo1.mapper.WeiboMapper;
import com.zyp.weibo_demo1.pojo.dto.WeiboDto;
import com.zyp.weibo_demo1.pojo.entity.Weibo;
import com.zyp.weibo_demo1.pojo.vo.ResultVo;
import com.zyp.weibo_demo1.pojo.vo.UserVo;
import com.zyp.weibo_demo1.pojo.vo.WeiboDetailVo;
import com.zyp.weibo_demo1.pojo.vo.WeiboIndexVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/weibo/")
public class WeiboController {

    @Autowired
    WeiboMapper mapper;

    @RequestMapping("/insert")
    public int insert(@RequestBody WeiboDto weiboDto, HttpSession session) {
        UserVo u = (UserVo) session.getAttribute("user");
        if (u==null) {
            return 2;
        }
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDto,weibo);
        weibo.setCreated(new Date());
        weibo.setUser_id(u.getId());
        mapper.insert(weibo);
        return 1;
    }

    @RequestMapping("select")
    public List<WeiboIndexVo> select() {
         return mapper.select();
    }

    @RequestMapping("selectById")
    public WeiboDetailVo selectById(int id){
        return mapper.selectById(id);
    }

    @RequestMapping("/select/mine")
    public ResultVo selectMine(HttpSession session) {
        UserVo u = (UserVo) session.getAttribute("user");
        if (u==null) {
            return new ResultVo(2,"用户未登录",null);
        }
        return new ResultVo(1,"请求成功",mapper.selectMine(u.getId()));
    }

    @Autowired
    CommentMapper commentMapper;

    @Value("${imagesPath}")
    private String dirPath;

    @RequestMapping("delete")
    public void delete(int id) {
        commentMapper.deleteByWeiboId(id);
        String url = mapper.selectById(id).getUrls();
        new File(dirPath+url).delete();
        mapper.deleteById(id);
    }
}
